package com.jd.fruit.controller.admin.shop;

import java.io.File;
import java.io.IOException;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.jd.fruit.common.annotation.Controller;
import com.jd.fruit.common.controller.BaseController;
import com.jd.fruit.common.handler.ServiceHandler;
import com.jd.fruit.common.util.DictUtil;
import com.jd.fruit.common.util.StringUtil;
import com.jd.fruit.model.admin.shop.Attribute;
import com.jd.fruit.model.admin.shop.Category;
import com.jd.fruit.model.admin.shop.Goods;
import com.jd.fruit.model.admin.shop.GoodsAttribute;
import com.jd.fruit.model.admin.shop.GoodsSku;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;

/**
 * 商品管理
 * 
 * @author lishunfeng
 * 
 */
@Controller("/admin/shop/goods")
public class GoodsController extends BaseController {
	/**
	 * 添加商品
	 */
	public void add() {
		Category category=null;
		String cid=this.getPara("cid");
		if(StrKit.notBlank(cid)){
		  category=Category.dao.findById(cid);
		  //查询对应的属性
		  List<Attribute> attributes=Attribute.dao.getAttrByCat(cid);
		  this.setAttr("attributes", attributes);
		  this.setAttr("category", category);
	    };
		this.setAttr("oprtype", DictUtil.oprSave);
		render("goods_add.html");
	}

	/**
	 * 选择分类
	 */
	public void chooseCategory() {
		this.setAttr("oprtype", DictUtil.oprSave);
		List<Category> categorys = Category.dao.getChildCat();
		this.setAttr("categorys", categorys);
		render("choose_category.html");
	}

	/**
	 *保存商品
	 */
	public void save() {
		// 保存
		Goods goods = getModel(Goods.class);
		String oprtyp = this.getPara("oprtype");
		String newGoodsId="";
		String delImageStr=this.getPara("delimage");
		if(oprtyp.equals(DictUtil.oprSave)){
			newGoodsId=Goods.dao.save(goods);
		}else{
			GoodsSku.dao.deleteById(goods.get("id")); 
			//如果没有上传图片或者没有修改过图片则不执行删除方法
			if(goods.get("goods_image")!=null&&!goods.get("goods_image").equals("")&&StrKit.notBlank(delImageStr)){ 
			//编辑修改时，删除之前上传的图片
			String delarry[]=delImageStr.split(";");
			String currentDelImage="";
			String rootPath=this.getSession().getServletContext().getRealPath(DictUtil.goods);
			for (int i = 0; i < delarry.length; i++) {
				currentDelImage=delarry[i];
				ServiceHandler.delFile(rootPath, currentDelImage);
			  }
		   }
		  goods.update();	
		}
		
		
		
		//商品SKU信息存储  待优化区域
		GoodsSku goodsSku=null;
		GoodsAttribute goodsattr=null;
		
		
		String[] attrFirst=this.getParaValues("attrFirst");
		String[] attrSecond=this.getParaValues("attrSecond");
		String[] attrThird=this.getParaValues("attrThird");
		
		String[] prices=this.getParaValues("price");
		String[] stockss=this.getParaValues("stocks");
		String[] saless=this.getParaValues("sales");
		String[] goodsImages=this.getParaValues("goods_image");
		//属性大类标识
		int normalTagFirst=prices.length / attrFirst.length;
		//属性从类标识
		Integer normalTagSecond = null; 
		if(null!=attrSecond && attrSecond.length>0){
			normalTagSecond=prices.length / attrSecond.length;
		}
		int tempTagFirst=0;
		int tempTagSecond=0;
		String attrStr="";
		for (int i = 0; i < prices.length; i++) {
			goodsSku=new GoodsSku();
			attrStr="";
			if(i!=0&&i%normalTagFirst==0){
				tempTagFirst+=1;
			}
			if(i!=0&&normalTagSecond!=null && i% normalTagSecond==0){
				tempTagSecond+=1;
			}
			//拼接保存属性对应的属性值串
		    if(null!=attrFirst && attrFirst.length>0){     
		    	attrStr+="#"+attrFirst[tempTagFirst];
		    }
		    if(null!=attrSecond && attrSecond.length>0){     
		    	attrStr+="#"+attrSecond[tempTagSecond];
		    } 
		    if(null!=attrThird && attrThird.length>0){     
		    	attrStr+="#"+attrThird[i];
		    }
		    goodsSku.set("goods_id",oprtyp.equals(DictUtil.oprSave)?newGoodsId:goods.get("id")); 
		    goodsSku.set("goods_image",goodsImages[tempTagFirst]!=null?goodsImages[tempTagFirst]:""); 
		    goodsSku.set("attr_value",attrStr);    
		    goodsSku.set("price",prices[i] != null?prices[i]:0);
		    goodsSku.set("stocks",stockss[i] != null?stockss[i]:0);
		    goodsSku.set("sales",saless[i] != null?saless[i]:0);
		    GoodsSku.dao.save(goodsSku);
		}
		
		
		
		
		this.redirect("/admin/shop/goods/list");
	}
	
	/**
	 * 编辑商品
	 */
	public void detail() {
		String id = StringUtil.getDcodePara(getRequest(), "id");
		Goods goods = Goods.dao.findById(id);
		String catId = goods.get("cat_id");
		Category category = Category.dao.findById(catId);
		// 属性
		List<Attribute> attributes = Attribute.dao.getAttrByCat(catId);
		this.setAttr("attributes", attributes);
		this.setAttr("category", category);
		this.getRequest().setAttribute("goods", goods);
		this.getRequest().setAttribute("oprtype", DictUtil.oprUpdate);
		render("goods_add.html");// 这个是页面的命名规范
	}


	/**
	 *商品数据列表
	 */
	public void list() {
		Goods goods=this.getModel(Goods.class);
		int pageNumber = this.getParaToInt(0,1);
		Page<Record> goodss = Goods.dao.list(pageNumber,DictUtil.default_pageSize,goods);
		this.setAttr("goodss", goodss);
		render("goods_list.html");
	}


	/**
	 * 删除商品
	 * 
	 * @throws IOException
	 */
	public void delete() throws IOException {
		String id = StringUtil.getDcodePara(getRequest(), "id");
		boolean isOk = Goods.dao.deleteById(id);
		if (isOk) {// 删除成功
			this.renderText(DictUtil.success);
		} else { // 删除失败
			this.renderText(DictUtil.failed);
		}
	}

	/**
	 * 上传图片信息
	 */
	public void uploadImage() {
		String delImgName = this.getPara("imgName");
		//获取上传文件
		UploadFile uf = getFile("Filedata", "shop/goods",DictUtil.maxImagSize,DictUtil.encoding);
	    //获取上传文件的类型  如 .jpg .png.....
		String imageType=uf.getFileName().substring(uf.getFileName().lastIndexOf("."),uf.getFileName().length());
	    String imageName=System.currentTimeMillis()+imageType;
		String rootPath =this.getSession().getServletContext().getRealPath(DictUtil.goods);
		//拼接重新生成的图片名字
		String file =rootPath+"/"+imageName;
	    //重命名
		uf.getFile().renameTo(new File(file));
		ServiceHandler.delFile(rootPath, delImgName);
		JSONObject urlJson = new JSONObject();
		urlJson.put("imgName", imageName);
		renderJson(urlJson.toJSONString());
	}
	

}
